package com.zhugang.week06;

/**
 * @program algorithms
 * @description: convertBST
 * @author: chanzhugang
 * @create: 2022/07/18 14:16
 */
public class ConvertBST {


    /**
     * 538 二叉搜索树转为累加树
     *
     * @param root
     * @return
     */

    private int sum = 0;

    public TreeNode convertBST(TreeNode root) {
        // 每个节点的新值 =  大于等于原节点的所有值累加  ： 中序遍历累加
        inorder(root);
        return root;
    }

    private void inorder(TreeNode root) {
        if (root == null) {
            return;
        }
        inorder(root.right);
        sum += root.val;
        root.val = sum;
        inorder(root.left);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}